package cn.zjh.system.service.impl;

import cn.zjh.basic.service.impl.BaseServiceImpl;
import cn.zjh.system.domain.Role;
import cn.zjh.system.mapper.RoleMapper;
import cn.zjh.system.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 添加重写
     * @param role
     */
    @Override
    @Transactional
    public void save(Role role) {
        super.save(role);
        addData(role);
    }

    /**
     * 添加修改重写
     * @param role
     */
    @Override
    @Transactional
    public void upDate(Role role){
        //先删除旧的权限
        roleMapper.delRoleMenuByRoIeId(role.getId());
        roleMapper.delRolePermissionByRoIeId(role.getId());
        //在添加新的权限
        addData(role);
        super.upDate(role);
    }

    /**
     * 删除重构
     * @param id
     */
    @Override
    @Transactional
    public void del(Long id){
        //删除中间的表数据
        roleMapper.delRoleMenuByRoIeId(id);
        roleMapper.delRolePermissionByRoIeId(id);
        roleMapper.delRoleEmployeeRoleByRoIeId(id);
        //有外键关联，先删除关联数据在删主表数据
        super.del(id);

    }

    //批量删除重构
    public void PatchDelete(Long[] ids){
        for (Long id : ids){
            del(id);
        }
    }

    //抽取公共方法供添加和修改的调用t_permission
    private void addData(Role role) {
        Long roleId = role.getId();

        List<Long> menus = role.getMenus();
        if (menus.size() > 0){
            roleMapper.addRoleMenu(roleId,menus);
        }
        List<Long> permissions = role.getPermissions();
        if (permissions.size() > 0){
            roleMapper.addRolePermissions(roleId,permissions);
        }

    }

}
